#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <fcntl.h>


void *transmitDmx();
void *changeValues();

unsigned char buffer[513];
    int red, green, blue;
main()
{
     pthread_t thread1, thread2;
     //char *message1 = "Thread 1";
     //char *message2 = "Thread 2";
     int  iret1, iret2;

    //fill the buffer with 0 (everything off)
    memset(buffer, '\0', 513);

    /* Create independent threads each of which will execute function */

     iret1 = pthread_create( &thread1, NULL, transmitDmx, NULL);
     iret2 = pthread_create( &thread2, NULL, changeValues, NULL);

     /* Wait till threads are complete before main continues. Unless we  */
     /* wait we run the risk of executing an exit which will terminate   */
     /* the process and all threads before the threads have completed.   */

     pthread_join( thread1, NULL);
     pthread_join( thread2, NULL); 

     printf("Thread 1 returns: %d\n",iret1);
     printf("Thread 2 returns: %d\n",iret2);
     exit(0);
}

void *transmitDmx()
{
    int fd;
    printf("Sending DMX \n");
    usleep(50000);
    fd = open("/dev/dmx0", O_WRONLY);
    if (fd < 0) {
	perror("/dev/dmx0 not found or busy");
	exit(-1);
    }
    while (1) {
	buffer[0] = 0;        //dit MOET 0 zijn
        buffer[1] = red;      //R strip 1
	buffer[2] = green;      //G strip 1
        buffer[3] = blue;      //B strip 1
	buffer[4] = 255;      //M strip 1
        buffer[5] = red;      //R strip 2
        buffer[6] = green;      //G strip 2
        buffer[7] = blue;      //B strip 2
        buffer[8] = 255;      //M strip 2

        write(fd, buffer, sizeof(buffer));
    }                      
}

void *changeValues()
{
    int tmpBlue, tmpRed, tmpGreen;
    printf("Changing Values! \n");
    
    while(1) {
	for(tmpGreen = green; tmpGreen > 1; tmpGreen--){
	    green = tmpGreen;
	    usleep(10000);
	}
	usleep(50000);
	for(tmpRed = red; tmpRed < 255; tmpRed++){
	    red = tmpRed;
	    usleep(10000);	
	}
	usleep(50000);
	for(tmpBlue = blue; tmpBlue > 1; tmpBlue--){
	    blue = tmpBlue;
	    usleep(10000);
	}
	usleep(50000);
	for(tmpGreen = green; tmpGreen < 255; tmpGreen++){
	    green = tmpGreen;
	    usleep(10000);
	}
	usleep(50000);
	for(tmpRed = red; tmpRed > 1; tmpRed--){
	    red = tmpRed;
	    usleep(10000);	
	}
	usleep(50000);
	for(tmpBlue = blue; tmpBlue < 255; tmpBlue++){
	    blue = tmpBlue;
	    usleep(10000);	
	}
	usleep(50000);
    }    
 
}
